#include <WiFiUdp.h>

// 接收端IP地址和端口
const uint16_t receiverPort = 8888;

WiFiUDP udp;            // 声明UDP对象
char packetBuffer[255]; // 用于存储UDP数据包的缓冲区

bool isCinfigurd = false;
unsigned long udpTick = 0; // 心跳

void configureUDP()
{
    if (!isCinfigurd)
    {
        udp.begin(receiverPort);
        isCinfigurd = true;
    }
}
void substringdata(String receivedData)
{
    int msgIndex = receivedData.indexOf("data=");
    if (msgIndex != -1)
    {
        String msgPart = receivedData.substring(msgIndex + 5);
        int firstHashIndex = msgPart.indexOf("#");
        int secondHashIndex = msgPart.indexOf("#", firstHashIndex + 1);
        if (firstHashIndex != -1 && secondHashIndex != -1)
        {
            String adcValueStr = msgPart.substring(0, firstHashIndex);
            String pressureStr = msgPart.substring(firstHashIndex + 1, secondHashIndex);
            String temperatureStr = msgPart.substring(secondHashIndex + 1);
            ShuiWeiValue = adcValueStr.toFloat();
            ShuiYaValue = pressureStr.toFloat();
            ShuiWenValue = temperatureStr.toFloat();
            // Serial.print("水位: ");
            // Serial.println(ShuiWeiValue);
            // Serial.print("压力: ");
            // Serial.println(ShuiYaValue);
            // Serial.print("温度: ");
            // Serial.println(ShuiWenValue);
        }
    }
}

void loop_UDP()
{
    if (WiFi.status() == WL_CONNECTED && millis() - udpTick >= 100)
    {
        // 获取上位机传递过来的数据长度
        int data_len = udp.parsePacket();
        // 如果长度非0，表示数据存在且有效
        if (data_len)
        {
            // 读取长度为255字节的数据并将他们保存到缓冲区buff里面
            int len = udp.read(packetBuffer, 255);
            // 由于长度不可能总是255，对于多出来的乱码部分采用截断处理
            if (len > 0)
            {
                packetBuffer[len] = 0;
                substringdata(packetBuffer);
            }
            sendtoTCPServer();
        }
        // udp.print("data=");
        // udp.print(ShuiWeiValue);
        // udp.print("#");
        // udp.print(ShuiYaValue);
        // udp.print("#");
        // udp.print(ShuiWenValue);
        // udp.endPacket(); // 发送数据
        udpTick = millis();
    }
}
